/**
 * https://leetcode.cn/problems/fruit-into-baskets/description/
 * 904.水果成篮
 * medium, 叶佳豪 2024.9.1
 * 滑动窗口
 */
class Solution {
public:
    int totalFruit(vector<int>& fruits) {
        int n=fruits.size();
        unordered_map<int,int> cnt;

        int i=0,sum=0;
        for(int j=0;j<n;j++){
            ++cnt[fruits[j]];
            while (cnt.size() > 2) {
                auto it = cnt.find(fruits[i]);
                --it->second;
                if (it->second == 0) {
                    cnt.erase(it);
                }
                ++i;
            }
            sum = max(sum, j - i + 1);
        }
        return sum;
    }
};